package com.haiertvbic.tvnow.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;

import com.haiertvbic.tvnow.util.SLog;

/**
 * 网络信息获取类
 */
public class WebData {

	private static final String TAG = "WebData";
	private HttpPost httpPost;
	private HttpResponse response;
	private DefaultHttpClient httpClient;

	public WebData(String url) {
		httpClient = new DefaultHttpClient();
		int timeout = 5000;
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
		httpClient.getParams().setParameter("http.socket.timeout", timeout);
		httpPost = new HttpPost(url);
	}

	public void setHeader(Map<String, String> headers) {
		for (Map.Entry<String, String> header : headers.entrySet()) {
			httpPost.addHeader(header.getKey(), header.getValue());
		}
	}

	/**
	 * 根据指定的URL和参数获取频道数据<br>
	 * 
	 * @param url
	 *            String<br>
	 * @param data
	 * <br>
	 * @return is InputStream<br>
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public InputStream PostDataStream(Map<String, String> data)
			throws ClientProtocolException, IOException {
		ArrayList<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
		for (Map.Entry<String, String> m : data.entrySet()) {
			postData.add(new BasicNameValuePair(m.getKey(), m.getValue()));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
		response = httpClient.execute(httpPost);
		// 测试连接情况
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != 200) {
			SLog.i(TAG, "资源不存在");
			// throw new Exception("资源不存在!");
		}
		HttpEntity httpEntity = response.getEntity();
		return httpEntity.getContent();
	}

	public HttpResponse getHeader() {
		// TODO Auto-generated method stub
		return response;
	}

	/**
	 * 把流转换为字符串。<br>
	 * 
	 * @param is
	 *            InputStream<br>
	 * @return str String<br>
	 */
	public String convertStreamToString(InputStream is) {
		// 字节流-->字符流
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			// 一行一行读取数据
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			SLog.i(TAG, e.toString());
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				SLog.i(TAG, e.toString());
			}
		}

		return sb.toString();
	}

}
